package com.stanwind.netty.handler.impl;

import com.stanwind.netty.api.ClientUtils;
import com.stanwind.netty.api.RoomUtils;
import com.stanwind.netty.core.protocol.model.Response;
import com.stanwind.netty.domain.pojo.Player;
import com.stanwind.netty.domain.pojo.Room;
import com.stanwind.netty.handler.Handler;
import com.stanwind.netty.serialize.ReadyState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * Created by StanWind on 2017/2/18.
 */
@Service
@Scope("prototype")
public class READY extends Handler {

    @Autowired
    private ClientUtils clientUtils;

    @Autowired
    private RoomUtils roomUtils;

    @Override
    public void handle() {
        Player player = clientUtils.getPlayer(getCtx());
        //玩家未登陆或者不在房间内
        if (player == null || player.getRoomId() < 1 || player.getSeatId() < 1)
            return;

        Room room =  roomUtils.getRoomByRoomId(player.getRoomId());
        //房间已经开始游戏
        if(room == null || room.isGame())
            return;

        player.setReady(true);

        Response response = new Response();
        ReadyState readyState = new ReadyState();
        readyState.setAccountId(player.getCharacter().getAccountId());
        response.setCmd(CMD_READY);
        response.setData(readyState.getBytes());

        roomUtils.boardResponse(player.getRoomId(), response);
        //检测是否可以开始游戏
        if(roomUtils.checkStart(player.getRoomId()))
            roomUtils.startGame(player.getRoomId());



    }
}
